import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io'; // Used for Platform detection

import 'package:flutter/services.dart';
import 'package:system_info_plus/system_info_plus.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _errorMessage = '';
  num? _deviceMemory; // Changed from int? to num? to accept both int and double
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _getDeviceMemory();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> _getDeviceMemory() async {
    try {
      // Add delay to ensure plugin has time to initialize
      await Future.delayed(const Duration(milliseconds: 500));

      // Get physical memory and handle possible type conversion
      try {
        final result = await SystemInfoPlus.physicalMemory;
        if (mounted) {
          setState(() {
            _deviceMemory = result;
            _isLoading = false;
          });
        }
      } on TypeError catch (e) {
        // Handle type mismatch by directly accessing the method channel
        debugPrint('Type error: $e, trying alternative approach');
        const channel = MethodChannel('dev/system_info_plus');
        final dynamic rawResult = await channel.invokeMethod('getMemorySpace');

        if (mounted) {
          setState(() {
            if (rawResult is int) {
              _deviceMemory = rawResult;
            } else if (rawResult is double) {
              _deviceMemory = rawResult;
            } else {
              _errorMessage = 'Unexpected data type: ${rawResult.runtimeType}';
            }
            _isLoading = false;
          });
        }
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _errorMessage = 'Error: $e';
          _isLoading = false;
        });
      }
      debugPrint('Error getting system info: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('SystemInfoPlus Example'),
          backgroundColor: Colors.blue,
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                if (_isLoading)
                  const CircularProgressIndicator()
                else if (_errorMessage.isNotEmpty)
                  Text(
                    _errorMessage,
                    style: const TextStyle(color: Colors.red, fontSize: 16),
                  )
                else
                  Text(
                    _deviceMemory != null
                        ? 'Device Memory: ${_deviceMemory.toString()} MB'
                        : 'Memory information unavailable',
                    style: const TextStyle(fontSize: 16),
                  ),
                const SizedBox(height: 20),
                Text(
                  'Platform Information:',
                  style: const TextStyle(
                      fontSize: 18, fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 10),
                Text('Operating System: ${Platform.operatingSystem}'),
                Text('OS Version: ${Platform.operatingSystemVersion}'),
                Text('Is Android: ${Platform.isAndroid}'),
                Text('Is iOS: ${Platform.isIOS}'),
                Text('Is macOS: ${Platform.isMacOS}'),
                Text('Is ohos: ${Platform.isOhos}'),
                const SizedBox(height: 20),
                ElevatedButton(
                  onPressed: () {
                    setState(() {
                      _isLoading = true;
                      _errorMessage = '';
                    });
                    _getDeviceMemory();
                  },
                  child: const Text('Refresh'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
